package com.sbxBase.service.impl;

import com.sbxBase.mapper.UserNoticeMapper;
import com.sbxBase.service.UserNoticeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.common.entity.sbxBase.UserNotice;
import com.common.utils.RequestUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Set;

/**
 * @Author: 何剑
 * @Date: 2023/3/13
 * @Note:
 **/
@Service
public class UserNoticeServiceImpl implements UserNoticeService {
    @Resource
    private UserNoticeMapper userNoticeMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserNotice(UserNotice userNotice) {
        if (userNotice.getCreated() == null) {
            userNotice.setCreated(new Date());
        }

        userNoticeMapper.insert(userNotice);
    }

    @Override
    public Page<UserNotice> pageUserNotice(Long pageIndex, Long pageSize, Boolean isRead, String event, String orderByName, Boolean orderBy) {
        String loginUserId = RequestUtil.getLoginUserId();
        Page<UserNotice> userNoticePage = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<UserNotice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(isRead, UserNotice::getOnRead, isRead);
        wrapper.eq(!StringUtils.isEmpty(event), UserNotice::getEvent, event);
        wrapper.eq(UserNotice::getReceiver, loginUserId);


//        wrapper.orderBy(!StringUtils.isEmpty(orderByName),orderBy,UserNotice::getCreated);
        if (orderBy) {
            wrapper.orderByAsc(UserNotice::getCreated);
        }else {
            wrapper.orderByDesc(UserNotice::getCreated);

        }

        userNoticePage = userNoticeMapper.selectPage(userNoticePage, wrapper);

        return userNoticePage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void readUserNotice(Set<String> noticeIds) {

        for (String noticeId : noticeIds) {
            UserNotice userNotice = new UserNotice();
            userNotice.setId(noticeId);
            userNotice.setOnRead(true);
            userNoticeMapper.updateById(userNotice);
        }

    }
}
